﻿using System;
using System.Linq;

using CommunityServer.Components;

using ATGi.CS.Facebook.Data;
using CommunityServer;

namespace ATGi.CS.Facebook.Components
{
    public class FacebookUsers
    {
        public static User GetCommunityUserFromFacebookUser(long facebookUserId)
        {
            using (var context = KernelContainer.Get<FBDataContext>())
            {
                var fuser = context.FacebookUsers.Where(fu => fu.FacebookID == facebookUserId).SingleOrDefault();
                if (fuser == null)
                    return null;
                else
                    return Users.GetUser(fuser.UserID, false, true);
            }
        }

        public static void AddFacebookUser(FacebookUser u)
        {
            using (var dc = KernelContainer.Get<FBDataContext>())
            {
                dc.FacebookUsers.InsertOnSubmit(u);
                dc.SubmitChanges();
            }
        }

        public static User AssociateFacebookUser(User user, IFacebookUser fbUser, IFacebookSession facebook)
        {
            if (user != null && fbUser.IsValid)
            {
                User writableUser = Users.GetUserWithWriteableProfile(user.UserID, user.Username, false);
                ATGi.CS.Facebook.Components.FacebookUser u = new ATGi.CS.Facebook.Components.FacebookUser();
                u.UserID = writableUser.UserID;
                u.FacebookID = fbUser.ID;
                u.Email = writableUser.Email;
                u.EmailHash = writableUser.FacebookEmailHash();
                u.LastAccessed = u.Created = DateTime.Now;

                FacebookUsers.AddFacebookUser(u);

                // Pull avatar image from facebook user.
                using (System.IO.MemoryStream s = new System.IO.MemoryStream())
                {
                    byte[] avatar = fbUser.ProfileImage(FacebookProfileImageSize.Large);
                    if (avatar != null)
                    {
                        s.Write(avatar, 0, avatar.Length);
                        writableUser.AvatarUrl = CommunityServer.Avatars.UpdateAvatar(writableUser.UserID, s);
                        writableUser.EnableAvatar = true;
                    }
                }

                // Save make sure the user is registered with Facebook for the friend linking that can be done
                facebook.RegisterUser(fbUser);

                // TODO: (JJE) what other information do we want to pull from facebook?
                Users.UpdateUser(writableUser);
                return writableUser;
            }
            return null;
        }
    }
}
